<script setup>
    import medicineApi from "@/api/medicine.js";
    import categoryApi from "@/api/category.js";
    import WangEditor from "@/components/WangEditor.vue";
    import {ref, reactive} from "vue";
    import {
        Delete,
        Edit,
        Plus,
        Download,
        Upload
    } from "@element-plus/icons-vue";
    import {ElMessage, ElMessageBox} from "element-plus";

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const medicineQuery = reactive({
        name: '',
        categoryId: '',
        leastSellPrice: '',
        mostSellPrice: '',
        page: 1,
        limit: 10
    })

    //加在所有药品类型
    const categories = ref([])
    const loadCategories = () => {
        categoryApi.selectAll().then(result => {
            categories.value = result.data
        })
    }
    loadCategories()

    const loadData = () => {
        medicineApi.list(medicineQuery).then(result => {
            list.value = result.data.list
            total.value = result.data.total
        })
    }

    loadData()

    const onSearch = () => {
        medicineQuery.page = 1;
        loadData();
    }

    //根据Id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            medicineApi.deleteById(id).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //批量删除
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        ids.value = rows.map(row => row.id);
        console.log(ids.value);
    }
    const deleteAll = () => {
        ElMessageBox.confirm(
            '确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            medicineApi.deleteAll(ids.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //添加和修改
    const dialogFormVisible = ref(false);
    const medicine = ref({})
    const title = ref()

    const showAddDialog = () => {
        dialogFormVisible.value = true
        title.value = '添加'
        medicine.value = {}
    }
    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        title.value = '编辑'
        medicine.value = {}
        medicineApi.selectById(id).then(result => {
            medicine.value = result.data
        })
    }

    const addOrUpdate = () => {
        if (medicine.value.id) {
            medicineApi.update(medicine.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        } else {
            medicineApi.add(medicine.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        }
    }

    //药品说明书
    const instructionTextVisible = ref(false);
    const showInstructionText = (id) => {
        instructionTextVisible.value = true
        medicine.value = {}
        medicineApi.selectById(id).then(result => {
            medicine.value = result.data
        })
    }

    import {useTokenStore} from "@/store/token.js";
    const tokenStore = useTokenStore();
    const headers = ref({
        //添加token
        Authorization: tokenStore.token
    })

    //富文本编辑器
    const onEditorChange = (instructions) => {
        medicine.value.instructions = instructions;
    }

    //导出Excel
    const exportExcel = () => {
        medicineApi.exportExcel().then(result => {
            let blob = new Blob([result], {type: "application/xlsx"});
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = "药品列表.xlsx";
            link.click();
            URL.revokeObjectURL(url);
        })
    }

    const success = () => {
        ElMessage({message: "导入成功", type: 'success',})
    }
</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-row>
                    <el-button type="primary" :icon="Plus" @click="showAddDialog">添加</el-button>
                    <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
                    <el-button :icon="Download" @click="exportExcel">导出Excel</el-button>
                    <el-upload
                        method="post"
                        action="api/medicine/importExcel"
                        name="file"
                        style="display:inline-block;margin-left:10px"
                        :show-file-list="false"
                        accept=".xlsx,.xls"
                        :on-success="success"
                        :headers="headers">
                        <el-button :icon="Upload">导入Excel</el-button>
                    </el-upload>
                </el-row>
            </div>
        </template>

        <el-form :inline="true">
            <el-form-item label="药品名称">
                <el-input v-model="medicineQuery.name" placeholder="请输入药品名称" clearable />
            </el-form-item>
            <el-form-item label="类别" style="width: 200px" :label-width="40">
                <el-select v-model="medicineQuery.categoryId" clearable placeholder="请选择类别">
                    <el-option
                        v-for="category in categories"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="售价">
                <el-input v-model="medicineQuery.leastSellPrice" placeholder="请输入最小售价" clearable />
            </el-form-item>
            <el-form-item>
                <el-input v-model="medicineQuery.mostSellPrice" placeholder="请输入最大售价" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="id" label="ID" width="100" />
            <el-table-column prop="name" label="药品名称"/>
            <el-table-column prop="sellPrice" label="售价"/>
            <el-table-column prop="categoryName" label="类别"/>
            <el-table-column prop="inventory" label="库存"/>
            <el-table-column prop="createTime" label="录入时间"/>
            <el-table-column prop="updateTime" label="更新时间"/>
            <el-table-column fixed="right" label="操作" align="center" min-width="100">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
                    <el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
                    <el-button type="success" plain @click="showInstructionText(row.id)">说明书</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="medicineQuery.page"
            v-model:page-size="medicineQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"/>

        <!--添加、编辑的弹出框-->
        <el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
            <el-form :model="medicine">
                <el-form-item label="药品名称" :label-width="70">
                    <el-input v-model="medicine.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="售价" :label-width="70">
                    <el-input v-model="medicine.sellPrice" autocomplete="off" />
                </el-form-item>
                <el-form-item label="类别" :label-width="70">
                    <el-select v-model="medicine.categoryId" clearable placeholder="请选择类别">
                        <el-option
                            v-for="category in categories"
                            :key="category.id"
                            :label="category.name"
                            :value="category.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="说明书" :label-width="70">
                    <WangEditor :initValue="medicine.instructions" @getEditorContent="onEditorChange"
                                v-if="dialogFormVisible" @close="dialogFormVisible = false"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!--药品说明书弹出框-->
        <el-dialog v-model="instructionTextVisible" title="药品说明书" width="70%" :lock-scroll="false">
            <el-form :model="medicine">
                <p v-html="medicine.instructions"/>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="instructionTextVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>